package com.example.ds.config;

import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;

/**
 * 全局异常处理
 *
 * @author 姚勇
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 用于全局处理控制器里的异常
     */
    @ExceptionHandler
    public ModelAndView handleException(Exception e) {
        ModelAndView modelAndView = new ModelAndView("error");
        modelAndView.addObject("errorMessage", e.getMessage());
        return modelAndView;
    }

    /**
     * 让全局的@RequestMapping都能获得在此设置的键值对
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        //model.addAttribute("msg", "额外信息");
    }

    /**
     * 用来设置WebDataBinder,WebDataBinder用来自动绑定前台请求参数到model中
     */
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        //webDataBinder.setDisallowedFields("id");
    }
}
